Tuples

Tuple is an immutable collection of elements (may be of same or different types), which is indexed by a 0-based integer. A 2-tuple can represent a point in 2-D plane, or a 3-Tuple can represent a point in 3-D plane.

Creating Tuples

  • Creating an empty tuple
x = ()  # () denotes a tuple type
       # or
       x = tuple()
  • Creating list with some initial elements
x = (2,3,0,'g')

In [1]:
x = (2,3)

In [2]:
x


Out[2]:
(2, 3)

In [3]:
x = (2,)  # x = (2) assigns int 2 to x. To make it a tuple, a comma is appended

In [4]:
x


Out[4]:
(2,)

In [5]:
x + (1,2)


Out[5]:
(2, 1, 2)

Tuples are immutable. So once a tuple is created, its contents are permanent unless it is reassigned with another tuple.

Tuples can also be Indexed and Sliced like lists


In [6]:
x


Out[6]:
(2,)

In [7]:
x = x + (1,3,4)   # Reassignment

In [8]:
x


Out[8]:
(2, 1, 3, 4)

In [9]:
x[1]


Out[9]:
1

In [10]:
x[2:5]


Out[10]:
(3, 4)

In [11]:
x[::-1]


Out[11]:
(4, 3, 1, 2)

Operations on Tuples

Since tuples are immutable, operations do not modify the original tuple

Here are some of the operations on list. They are member functions of class tuple. If x is a tuple,

  • x.index(ele) - searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use in to check without a ValueError).
  • x.count(ele) - counts the number of occurances of ele in x

Membership operator in is also supported


In [12]:
x


Out[12]:
(2, 1, 3, 4)

In [13]:
2 in x


Out[13]:
True

In [14]:
x.count(2)


Out[14]:
1

In [17]:
x.index(3)


Out[17]:
2

Using a list of tuples, one can model a collection of points in space